﻿using hedefgrup.reports.renault;
using hedefgrup.reports.renault.calculators;
using hedefgrup.reports.renault.database;
using hedefgrup.reports.renault.date;
using hedefgrup.reports.renault.definitions;
using System;
using System.Configuration;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;

public class reportPage : Page
{
    protected calculatorType calculationType;
    protected int cumulativeMonths;
    protected reportMonth endMonth;
    private const string NON_VIRTUAL_DEALER_TYPE_CODES = "[dealer][branch][satellite][connected_point]";
    private int renderElapsedTime = 0;
    private DateTime renderStartTime = DateTime.Now;
    protected reportMonth selectedMonth;
    protected reportMonth startMonth;
    protected dealerDefinition targetDealer;

    protected void ensureAdministratorIsLoggedIn()
    {
        this.ensureUserIsLoggedIn();
        if (!user.Current.getIsAdministrator())
        {
            base.Response.Redirect("/forms/common/default.aspx");
        }
    }

    protected void ensureUserIsLoggedIn()
    {
        if (user.Current == null)
        {
            if (string.IsNullOrEmpty(this.getString("user_name")) || string.IsNullOrEmpty(this.getString("password")))
            {
                base.Response.Redirect("/forms/common/login.aspx?err=e");
            }
            user matchingUser = user.getUserByCredentials(this.getString("user_name"), this.getString("password"));
            if (matchingUser == null)
            {
                base.Response.Redirect("/forms/common/login.aspx?err=u");
            }
            if (!matchingUser.getIsActive())
            {
                base.Response.Redirect("/forms/common/login.aspx?err=a");
            }
            user.Current = matchingUser;
            this.Session["8152790D-E7BA-45f7-AE1D-F209A7BE1A4C"] = this.getString("project_selection");
            base.Response.Redirect("/forms/common/default.aspx");
        }
    }

    public reportCalculator getCalculator()
    {
        return getDataCache().reportCalculator;
    }

    protected calculatorType getCalculatorType()
    {
        return (calculatorType)Enum.Parse(typeof(calculatorType), this.getString("ct"));
    }

    protected string getCalculatorTypeDescription()
    {
        switch (this.calculationType)
        {
            case calculatorType.dealersAndSatellitesJoined:
                return "Y.Satıcı ve Uydu k\x00fcm\x00fclatif";

            case calculatorType.dealersAndSatellites:
                return "Y.Satıcı ve Uydu detaylı";

            case calculatorType.connectedPoints:
                return "Bağlı Noktalar";

            case calculatorType.network2:
                return "Şebeke 2";

            case calculatorType.network1:
                return "Şebeke 1";

            case calculatorType.allnetworks:
                return "Şebeke 1 + Şebeke 2";
        }
        return "";
    }

    protected string getCalculatorTypeShortDescription()
    {
        switch (this.calculationType)
        {
            case calculatorType.dealersAndSatellitesJoined:
            case calculatorType.network1:
                return "SEBEKE 1";

            case calculatorType.dealersAndSatellites:
                return "SEBEKE 3";

            case calculatorType.connectedPoints:
            case calculatorType.network2:
                return "SEBEKE 2";
        }
        return "";
    }

    protected string getConnectionString()
    {
        return ConfigurationManager.ConnectionStrings["report_db"].ConnectionString;
    }

    protected int getCumulativeMonths()
    {
        return this.getInt("c");
    }

    protected dataCache getDataCache()
    {
        if (!string.IsNullOrEmpty(this.advancedFilter))
        {
            return dataCache.getNamedInstance(this.userProjectName + "_" + this.makeSelection + "_" + this.advancedFilter);
        }

        dataCache matchingDataCache = dataCache.getDataCacheByProjectName(this.userProjectName, this.makeSelection);

        if (matchingDataCache == null)
        {
            return null;
        }

        if (!string.IsNullOrEmpty(this.salesPerson))
        {
            return getSalesPersonDataCache(matchingDataCache, this.salesPerson);
        }

        return matchingDataCache;
    }

    protected dataCache getSalesPersonDataCache(dataCache sourceDataCache, string salesPersonName)
    {
        string dataName = userProjectName + "_" + makeSelection + "_" + salesPerson;
        string dataFetchFilter = sourceDataCache.dataFetchFilter;
        dataFetchFilter += (string.IsNullOrEmpty(dataFetchFilter) ? "" : " AND ") + "SATICI = '" + salesPersonName + "'";

        sourceDataCache.createVirtualDataCache(dataName, this.userProjectName, dataName, sourceDataCache.dataTableName, dataFetchFilter);

        return dataCache.getNamedInstance(dataName);
    }

    protected string salesPerson
    {
        get
        {
            return getString("sp");
        }
    }

    protected dealerDefinition getDealer()
    {
        return this.getDataCache().getDealer(this.getString("d"));
    }

    protected int getElapsedRenderTime()
    {
        return this.renderElapsedTime;
    }

    protected int getInt(string key)
    {
        return Convert.ToInt32(this.getString(key));
    }

    protected reportMonth getReportEndMonth()
    {
        return new reportMonth(this.getInt("e"));
    }

    protected virtual string getReportFileName()
    {
        StringBuilder sb = new StringBuilder();
        if (!string.IsNullOrEmpty(this.getString("d")))
        {
            sb.AppendFormat("{0} {1} - ", this.getDealer().getCode().Replace(".", "_"), this.getDealer().getName().Replace(".", "_"));
        }
        if (!string.IsNullOrEmpty(this.getString("m")))
        {
            sb.AppendFormat("{0} {1:0000} - ", this.getReportMonth().getMonthName(), this.getReportMonth().getYear());
        }
        if (!string.IsNullOrEmpty(this.getString("e")))
        {
            sb.AppendFormat("{0} {1:0000} - ", this.getReportEndMonth().getMonthName(), this.getReportEndMonth().getYear());
        }
        sb.AppendFormat("{0} - ", this.getCalculatorTypeShortDescription());
        sb.AppendFormat("{0} AYLIK", this.getCumulativeMonths());
        return sb.ToString().Replace("ğ", "g").Replace("\x00fc", "u").Replace("ş", "s").Replace("ı", "i").Replace("\x00f6", "o").Replace("\x00e7", "c").Replace("Ğ", "G").Replace("\x00dc", "U").Replace("Ş", "S").Replace("İ", "I").Replace("\x00d6", "O").Replace("\x00c7", "C");
    }

    protected reportMonth getReportMonth()
    {
        return new reportMonth(this.getInt("m"));
    }

    private reportMonth getReportMonth(string key)
    {
        return new reportMonth(this.getInt(key));
    }

    protected reportMonth getReportStartMonth()
    {
        return new reportMonth(this.getInt("s"));
    }

    protected string getString(string key)
    {
        return base.Request[key];
    }

    protected string[] getUserDealerCodes()
    {
        this.ensureUserIsLoggedIn();
        return user.Current.getDealerCodes();
    }

    protected string GetVerbatimFilter()
    {
        if (this.userProjectName == Global.PROJECT_QVO)
        {
            return "MARKA LIKE 'QVO%'";
        }
        if (this.makeSelection == Global.MAKE_RENAULT)
        {
            return "MARKA LIKE 'Renault%'";
        }
        if (this.makeSelection == Global.MAKE_DACIA)
        {
            return "MARKA LIKE 'Dacia%'";
        }
        if (this.makeSelection == Global.MAKE_RENAULT_AND_DACIA)
        {
            return "(MARKA LIKE 'Renault%' OR MARKA LIKE 'Dacia%')";
        }
        if (this.makeSelection == Global.MAKE_RENAULT_PRIVATE)
        {
            return "MARKA LIKE 'Renault Binek%'";
        }
        if (this.makeSelection == Global.MAKE_RENAULT_COMMERCIAL)
        {
            return "MARKA LIKE 'Renault Ticari%'";
        }
        return "1 = 2";
    }

    protected static string getXmlDefinitionFilePath(string projectName, string make)
    {
        string dataFileName = HttpContext.Current.Server.MapPath("/x/" + projectName + make + ".xml");
        if (!File.Exists(dataFileName))
        {
            dataFileName = HttpContext.Current.Server.MapPath("/x/" + projectName + ".xml");
            if (!File.Exists(dataFileName))
            {
                throw new FileNotFoundException("The question definition file for project " + projectName + " and make " + make + " could not be found");
            }
        }
        return dataFileName;
    }

    protected void initialize()
    {
        db.setConnectionString(this.getConnectionString());
        reloadAll(false);
        base.Response.Expires = -1;
        if (!string.IsNullOrEmpty(base.Request.Form["c"]))
        {
            try
            {
                this.cumulativeMonths = this.getCumulativeMonths();
            }
            catch
            {
            }
        }
        if (!string.IsNullOrEmpty(base.Request.Form["d"]))
        {
            try
            {
                this.targetDealer = this.getDealer();
            }
            catch
            {
            }
        }
        if (!string.IsNullOrEmpty(base.Request.Form["s"]))
        {
            try
            {
                this.startMonth = this.getReportStartMonth();
            }
            catch
            {
            }
        }
        if (!string.IsNullOrEmpty(base.Request.Form["e"]))
        {
            try
            {
                this.endMonth = this.getReportEndMonth();
            }
            catch
            {
            }
        }
        if (!string.IsNullOrEmpty(base.Request.Form["m"]))
        {
            try
            {
                this.selectedMonth = this.getReportMonth();
            }
            catch
            {
            }
        }
        if (!string.IsNullOrEmpty(base.Request.Form["ct"]))
        {
            try
            {
                this.calculationType = this.getCalculatorType();
            }
            catch
            {
            }
        }
        if (this.IsExcelDownloadRequest)
        {
            base.Response.ContentType = "application/vnd.ms-excel";
            base.Response.AddHeader("content-disposition", "attachment; filename=" + this.getReportFileName() + ".xls");
            base.Response.ContentEncoding = Encoding.UTF8;
        }
    }

    protected bool isAdministrativeLogin()
    {
        return ((user.Current != null) && user.Current.getIsAdministrator());
    }

    protected bool isDelaer()
    {
        return ((user.Current != null) && user.Current.getAuthLevel() == "dealer");
    }

    public static void reloadAll(bool force)
    {
        dataCache.load(HttpContext.Current.Server.MapPath("/x/data.xml"), force);
    }

    protected void RenderComplete()
    {
        this.renderElapsedTime = Convert.ToInt32(DateTime.Now.Subtract(this.renderStartTime).TotalMilliseconds);
    }

    protected string advancedFilter
    {
        get
        {
            return base.Request.Form["flt"];
        }
    }

    protected bool IsExcelDownloadRequest
    {
        get
        {
            return (base.Request.Form["IsExcelDownloadRequest"] == "1");
        }
    }

    protected string makeSelection
    {
        get
        {
            if (!string.IsNullOrEmpty(base.Request.Form["make"]))
            {
                this.makeSelection = base.Request.Form["make"];
            }
            if (this.Session["1734DB0D-AD4E-4345-A5CE-F4C7195E04CE"] == null)
            {
                this.makeSelection = "RenaultAndDacia";
            }
            return Convert.ToString(this.Session["1734DB0D-AD4E-4345-A5CE-F4C7195E04CE"]);
        }
        set
        {
            this.Session["1734DB0D-AD4E-4345-A5CE-F4C7195E04CE"] = value;
        }
    }

    protected string userProjectName
    {
        get
        {
            return Convert.ToString(this.Session["8152790D-E7BA-45F7-AE1D-F209A7BE1A4C"]);
        }
        set
        {
            this.Session["8152790D-E7BA-45F7-AE1D-F209A7BE1A4C"] = value;
        }
    }
}

